import cv2
import numpy as np
import matplotlib.pyplot as plt

filename = 'grid.jpg'
src = cv2.imread(filename, cv2.IMREAD_COLOR)
src = cv2.cvtColor(src, cv2.COLOR_BGR2RGB)
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)

# Sobel边缘
sobel_x = cv2.Sobel(gray, 2, 1, 0, ksize=3)
sobel_y = cv2.Sobel(gray, 2, 0, 1, ksize=3)
sobel = np.abs(sobel_x) + np.abs(sobel_y)

# Laplacian边缘
laplacian = cv2.Laplacian(gray, 2, ksize=3)

# Canny边缘
canny = cv2.Canny(gray, 50, 150)

# 显示原始图像
ax1 = plt.subplot(221)
ax1.set_title('Src')
plt.imshow(src),    plt.xticks([]), plt.yticks([])
# 显示边缘提取图像
ax2 = plt.subplot(222)
ax2.set_title('Sobel')
plt.imshow(sobel, cmap='gray'), plt.xticks([]), plt.yticks([])
ax3 = plt.subplot(223)
ax3.set_title('Laplacian')
plt.imshow(laplacian, cmap='gray'), plt.xticks([]), plt.yticks([])
ax4 = plt.subplot(224)
ax4.set_title('Canny')
plt.imshow(canny, cmap='gray'), plt.xticks([]), plt.yticks([])
plt.show()
